package com.zh.chat.monitor;

import java.io.File;
import java.util.TimerTask;

/**
 * 文件监控任务
 * @author 逍遥の剑仙
 * 2013-3-3
 */
public final class FileMonitorTask extends TimerTask {

    private FileChangeListener listener;
    private String filename;
    private File monitingFile;
    private long lastModified;
    private boolean exists;

    public FileMonitorTask(FileChangeListener listener, String filename) {
        this.listener = listener;
        this.filename = filename;

        this.monitingFile = new File(filename);
        if (!this.monitingFile.exists()) {
            return;
        }

        this.lastModified = this.monitingFile.lastModified();
    }

    @Override
    public void run() {
        long latestChange = this.monitingFile.lastModified();
        boolean exists = this.monitingFile.exists();
        
        if(this.exists != exists){
        	this.exists = exists;
        	if(exists){
        		this.listener.fileExist(this.filename);
        		this.lastModified = latestChange;
        	}else{
        		this.listener.fileNotExist(filename);
        		this.lastModified = latestChange;
        	}
        	return;
        }
        if (this.lastModified != latestChange) {
            this.lastModified = latestChange;
            this.listener.fileChanged(this.filename);
            return;
        }
    }
}
